/*
 * This file is part of Annuaire.
 *
 * Annuaire is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Annuaire is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Annuaire.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.miage.annuaire.pdf;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;


import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;

import org.w3c.dom.*;
import java.io.*;


/**
 * Convertie un fichier XML en annuaire au format PDF.
 * Le document XML doit respecter le shema décrit dans le fichier data.xsd
 * Le style du ficheir PDF est decrit dans le fichier pdf.xsl
 *
 * @author comeulie
 */
public class xml2pdf {

    /**
     * Chemein vers les ficheirs de configuration. 
     * N'est utilile seulement pour les tests en local.
     */
    static File baseDir = new File("./web/WEB-INF/configurationXML/");

    /**
     * Convertie le fichier XML en PDF, vers un InputStream
     * @param nodeXML : node vers le ficheir XML
     * @param xsl :     chemin vers les fichiers de configuration
     * @param path :    chemin vers le repertoire "resouces" pour les images
     * @return :        fichier resultat PDF au format InputStream
     */
    public FileInputStream extract2stream(Node nodeXML, InputStream xsl, String path) {
        OutputStream out = null;
        File pdffile = null;
        FileInputStream in = null;       
        try {
            pdffile = File.createTempFile("nom",".tmp");
            pdffile.deleteOnExit();      
            FopFactory fopFactory = FopFactory.newInstance();
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(pdffile));
            try {
                Fop fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, foUserAgent, out);
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(xsl));

                transformer.setParameter("versionParam", "2.0");
                transformer.setParameter("pathParam", path);
                DOMSource src = new DOMSource( nodeXML );
                Result res = new SAXResult(fop.getDefaultHandler());
                transformer.transform(src, res);
            } finally {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
        try {
            in = new java.io.FileInputStream(pdffile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(xml2pdf.class.getName()).log(Level.SEVERE, null, ex);
        }
        return in;
    }

    /**
     * Convertie le fichier XML en PDF, vers un fichier sur le disque
     * @param nodeXML : fichier XML
     * @param name :    nom du fichier PDF
     * @return :        fichier resultat PDF au format InputStream
     */
    public FileInputStream extract2file(Node nodeXML, String name) {
        FileInputStream resultFile = null;
        File pdffile = null;
        File outDir = new File(baseDir, "out");
        outDir.mkdirs();
        try {
            File xsltfile = new File(baseDir, "pdf.xsl");
            pdffile = new File(outDir, name);
            FopFactory fopFactory = FopFactory.newInstance();
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            OutputStream out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(pdffile));
            try {
                Fop fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, foUserAgent, out);
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
                transformer.setParameter("versionParam", "2.0");
                DOMSource src = new DOMSource( nodeXML );
                Result res = new SAXResult(fop.getDefaultHandler());
                transformer.transform(src, res);
            } finally {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
        try {
            resultFile = new java.io.FileInputStream(pdffile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(xml2pdf.class.getName()).log(Level.SEVERE, null, ex);
        }
        return resultFile;
    }
}
